package com.eightbears.beboy.ui.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.MainActivity;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.HomeListAdapter;
import com.eightbears.beboy.base.BaseFragment;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.SharesUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.GetBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.banner.LocalImageHolderView;
import com.eightbears.beboy.base.view.basepopu.BasePopupWindow;
import com.eightbears.beboy.base.view.citypicker.CityPickerActivity;
import com.eightbears.beboy.base.view.image.ui.ImageViewActivity;
import com.eightbears.beboy.base.view.image.view.ImageItem;
import com.eightbears.beboy.base.view.image.view.ImagePicker;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.popupwindow.ClassifyPopup;
import com.eightbears.beboy.base.view.popupwindow.MultipeSelectionPopup;
import com.eightbears.beboy.entity.BannerEntity;
import com.eightbears.beboy.entity.ClassifyEntity;
import com.eightbears.beboy.entity.CommonEntity;
import com.eightbears.beboy.entity.HomeListEntity;
import com.eightbears.beboy.entity.LocationEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.ui.activity.ChatActivity;
import com.eightbears.beboy.ui.user.activity.PaymentActivity;
import com.eightbears.beboy.ui.user.activity.PostDetailActivity;
import com.eightbears.beboy.ui.user.activity.PublishContentsActivity;
import com.eightbears.beboy.ui.user.activity.RepostPostActivity;
import com.eightbears.beboy.ui.user.activity.SearchPostActivity;
import com.eightbears.beboy.ui.user.activity.ShopDetailActivity;
import com.eightbears.beboy.ui.user.activity.UserInfoActivity;
import com.eightbears.greendao.District;
import com.eightbears.greendao.Friends;
import com.hyphenate.chat.EMClient;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;
import static com.eightbears.beboy.MainActivity.EVENT_VIP_CANCEL;
import static com.eightbears.beboy.base.cache.DistrictCache.CODE_CITY;
import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_BANNERS;
import static com.eightbears.beboy.base.util.CommonAPI.URL_BLACKLIST;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FAV_UNFAV;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FOLLOW_UNFOLLOW;
import static com.eightbears.beboy.base.util.CommonAPI.URL_INVITATION;
import static com.eightbears.beboy.base.util.CommonAPI.URL_POST_LIKE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_REPOT;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.ByVipActivity.EVENT_UPDATE_USER_STATUS;
import static com.eightbears.beboy.ui.user.activity.PostDetailActivity.EVENT_DELETE_POST;
import static com.eightbears.beboy.ui.user.activity.RepostPostActivity.EVENT_PARAMS_COMMENT;
import static com.eightbears.beboy.ui.user.activity.RepostPostActivity.EVENT_PARAMS_LIKE;
import static com.eightbears.beboy.ui.user.activity.RepostPostActivity.EVENT_PARAMS_REPOST;
import static com.eightbears.beboy.ui.user.activity.SettingActivity.EVENT_USER_HEAD_UPDATE;
import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;
import static com.eightbears.beboy.ui.user.fragment.FindFragment.PARAMS_SHOP_ID;

public class HomeFragment extends BaseFragment implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, OnItemClickListener {

    public static final String EVENT_SHARED_SUCCESS = "shareSuccess";
    public static final String EVENT_PUBLISH_POST_SUCCESS = "postPublishSuccess";
    public static final String EVENT_BUY_POST_SUCCESS = "buyPostSuccess";
    public static final String EVENT_BUY_VIP_SUCCESS = "buyVipSuccess";
    public static final String EVENT_DELETE_COMMENT = "deleteComment";
    public static final String EVENT_CHANGE_CITY = "changeCity";

    public static final int PARAMS_REQUEST_TYPE_NEW = 0;
    public static final int PARAMS_REQUEST_TYPE_BUY = 1;
    public static final int PARAMS_REQUEST_TYPE_COLLECT = 2;
    public static final int PARAMS_REQUEST_TYPE_LOCALTION = 3;
    public static final int PARAMS_REQUEST_TYPE_HOT = 4;
    public static final int PARAMS_REQUEST_TYPE_KEY = 5;
    public static final int PARAMS_REQUEST_TYPE_FOLLOW = 6;
    public static final String PARAMS_BUY_POST = "buyPost";
    public static final String PARAMS_POST_ID = "postId";
    public static final String PARAMS_POST_ITEM = "postItem";

    private static final int REQUEST_CODE_PICK_CITY = 233;

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    //    @BindView(R.id.iv_user_head)
//    ImageView iv_user_head;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.ll_float_new_publish)
    LinearLayout ll_float_new_publish;
    @BindView(R.id.ll_float_location)
    LinearLayout ll_float_location;
    @BindView(R.id.ll_float_hot)
    LinearLayout ll_float_hot;
    @BindView(R.id.ll_float_follow)
    LinearLayout ll_float_follow;
    @BindView(R.id.view_title)
    View view_title;
    @BindView(R.id.view_empty)
    View view_empty;
    @BindView(R.id.view_menu)
    View view_menu;
    @BindView(R.id.iv_icon)
    ImageView iv_icon;
    @BindView(R.id.tv_page_title)
    TextView tv_page_title;
    @BindView(R.id.view_top)
    View view_top;

    private View view_head_menu;
    private LinearLayout ll_new_publish;
    private LinearLayout ll_hot;
    private LinearLayout ll_location;
    private LinearLayout ll_follow;
    private ConvenientBanner mConvenientBanner;

    private int page = 1;
    private int requestType = 0;
    private boolean isErr = true;
    private int isEnd = 0;
    private List<String> bannerImages;

    private UserEntity mUserEntity;
    private Friends friends;
    private LocationEntity userLocation;
    private ClassifyEntity classifyEntity;
    private HomeListEntity.Post post;
    private MultipeSelectionPopup multipeSelectionPopup;
    private ClassifyPopup classifyPopup;
    private Animation mUpAnimation, mDownAnimation;
    private BannerEntity bannerEntity;

    private HomeListAdapter homeListAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
        return view;
    }

    @Override
    protected void initView() {
        mUserEntity = SPUtil.getUser();
        userLocation = SPUtil.getUserLocation();
        classifyEntity = new ClassifyEntity("0", "全部");
        SPUtil.putSelClass(classifyEntity);
        KLog.e("初始化HomeFragment");
        if (userLocation.getCityName() != null) {
            tv_address.setText(userLocation.getCityName() + "");
        }
        mUpAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.up_rotate);
        mDownAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.down_rotate);
        MainActivity parentActivity = (MainActivity) getActivity();
        showHead();
        initAdapter();
        newPublishSel();
    }

    @Override
    protected void initData() {
        bannerImages = new ArrayList<>();
        getData();
        getBanner();
    }

    @Override
    protected void initEvent() {
        rv_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int totleDy = 0;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totleDy = getScollYDistance();
                if (totleDy >= 350) {
                    view_menu.setVisibility(View.VISIBLE);
                    view_head_menu.setVisibility(View.GONE);
                } else {
                    view_menu.setVisibility(View.GONE);
                    view_head_menu.setVisibility(View.VISIBLE);
                }
            }
        });

        //查看图片
        homeListAdapter.setOnImageClickListener(new HomeListAdapter.OnClickImageItemListener() {
            @Override
            public void onImageClick(BaseQuickAdapter baseViewHolder, View view, int i) {
                Intent intentPreview = new Intent(getActivity(), ImageViewActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) baseViewHolder.getData());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, i);
                startActivity(intentPreview);
                getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
            }
        });

        // 购买帖子
        homeListAdapter.setOnByContentClickListener(new HomeListAdapter.OnByContentClickListener() {
            @Override
            public void onByClick(BaseQuickAdapter baseQuickAdapter, View view, int i, String type) {
                post = (HomeListEntity.Post) baseQuickAdapter.getData().get(i);
                switch (type) {
                    case HomeListAdapter.STATUS_BUY_CONTENT:
                        startLocalActivity(PaymentActivity.class, PARAMS_BUY_POST, post);
                        break;
                    case HomeListAdapter.STATUS_SHOW_CONTENT:
                        startLocalActivity(PostDetailActivity.class, PARAMS_POST_ID, post.getId());
                        break;
                }
            }
        });

        homeListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                post = (HomeListEntity.Post) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.ll_btn_like:  // 点赞
                        executeLike();
                        break;
                    case R.id.ll_btn_share:  // 分享
                        SharesUtil.shareContent(getActivity(), post.getId());
                        break;
                    case R.id.ll_btn_comment://帖子详情
                        startLocalActivity(PostDetailActivity.class, PARAMS_POST_ID, post.getId());
                        break;
                    case R.id.ll_btn_repost://转发
                        post.setReport(true);
                        startLocalActivity(RepostPostActivity.class, PARAMS_POST_ITEM, post);
                        break;
                    case R.id.ll_follow_drop_down:  // 下拉菜单
                        dropDownMenu();
                        break;
                    case R.id.iv_user_head:
                        startLocalActivity(UserInfoActivity.class, PARAMS_USER_INFO, post.getUser_id());
                        break;
                }
            }
        });
    }

    /**
     * 初始化banner数据
     */
    public void initBannerData() {
        mConvenientBanner.setPages(new CBViewHolderCreator<LocalImageHolderView>() {
            @Override
            public LocalImageHolderView createHolder() {
                return new LocalImageHolderView();
            }
        }, bannerImages)
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setOnItemClickListener(this);

        if (bannerImages.size() <= 1) {
            mConvenientBanner.setCanLoop(false);
        } else {
            mConvenientBanner.setCanLoop(true);
        }
    }

    public void initClassifyPopup() {
        classifyPopup = new ClassifyPopup(getActivity());
        classifyPopup.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mDownAnimation.setFillAfter(true);
                iv_icon.startAnimation(mDownAnimation);
            }
        });

        classifyPopup.setOnClickItemListener(new ClassifyPopup.OnClicktemListener() {
            @Override
            public void onClickItem(ClassifyEntity mClassifyEntity) {
                classifyEntity = mClassifyEntity;
                SPUtil.putSelClass(mClassifyEntity);
                tv_page_title.setText(classifyEntity.getClassifyName());
                page = 1;
                homeListAdapter.getData().clear();
                getData();
            }
        });
    }

    @OnClick(R.id.tv_address)
    void pickerCity() {
        startActivityForResult(new Intent(getActivity(), CityPickerActivity.class), REQUEST_CODE_PICK_CITY);
        getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }


    //用户头像事件
//    @OnClick(R.id.iv_user_head)
//    void showLeft() {
//        parentActivity.showLeftMenu();
//    }

    @OnClick(R.id.rl_classes)
    void classes() {
        mUpAnimation.setFillAfter(true);
        iv_icon.startAnimation(mUpAnimation);
        initClassifyPopup();
        if (classifyPopup.isShowing()) {
            classifyPopup.dismiss();
        } else {
            classifyPopup.showDropDown(view_top);
        }
    }

    // 搜索
    @OnClick(R.id.ll_publish_search)
    void search() {
        startLocalActivity(SearchPostActivity.class);
    }

    /**
     * 点击打开发表图标页面
     */
    @OnClick(R.id.ll_publish_message)
    void publishButton() {
        startLocalActivity(PublishContentsActivity.class);
    }

    //初始化适配器
    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setProgressViewOffset(true, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(getContext()));
        homeListAdapter = new HomeListAdapter(getContext());
        homeListAdapter.openLoadAnimation();
        homeListAdapter.addHeaderView(getHeaderView());
        homeListAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(homeListAdapter);
    }

    private View getHeaderView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.head_post, null);
        view_head_menu = view.findViewById(R.id.view_head_menu);
        ll_new_publish = (LinearLayout) view.findViewById(R.id.ll_float_new_publish);
        ll_hot = (LinearLayout) view.findViewById(R.id.ll_float_hot);
        ll_location = (LinearLayout) view.findViewById(R.id.ll_float_location);
        ll_follow = (LinearLayout) view.findViewById(R.id.ll_float_follow);
        mConvenientBanner = (ConvenientBanner) view.findViewById(R.id.convenientBanner);
        initHeadEvent();
        return view;
    }

    private void initHeadEvent() {
        ll_new_publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getNewPublishData();
            }
        });

        ll_hot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getHotData();
            }
        });

        ll_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocationData();
            }
        });

        ll_follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFollowData();
            }
        });
    }

    /**
     * 菜单
     */
    private void dropDownMenu() {
        friends = FriendsCache.getInstance(getActivity()).getCacheById(post.getUser_id());
        String followText = post.getIs_follow() == 1 ? getString(R.string.text_unfollow) : getString(R.string.text_follow);
        String collectText = post.getFav() == 1 ? getString(R.string.text_remove_fav) : getString(R.string.text_fav);
        String addFriendText = friends == null ? getString(R.string.add_friend) : getString(R.string.text_start_chat);

        if (null == multipeSelectionPopup) {
            multipeSelectionPopup = new MultipeSelectionPopup(getActivity());
            multipeSelectionPopup.setOnClickItemListener(new MultipeSelectionPopup.OnClicktemListener() {
                @Override
                public void onClickItem(View v) {
                    switch (v.getId()) {
                        case R.id.ll_1:
                            executeFollow();
                            break;
                        case R.id.ll_2:
                            executeFav();
                            break;
                        case R.id.ll_3:
                            addFriend();
                            break;
                        case R.id.ll_4:
                            executeBlack();
                            break;
                        case R.id.ll_5:
                            executeReport();
                            break;
                        case R.id.ll_6:
                            deletePost();
                            break;
                    }
                }
            });
        }
        if (post.getUser_id().equals(mUserEntity.getData().getUser_id())) {
            multipeSelectionPopup.setTx_6Text(getString(R.string.text_delete));
        } else {
            multipeSelectionPopup.setTx_1Text(followText);//关注
            multipeSelectionPopup.setTx_2Text(collectText);//收藏
            multipeSelectionPopup.setTx_3Text(addFriendText);//加好友
            multipeSelectionPopup.setTx_4Text(getString(R.string.Move_into_the_blacklist_new));//加入黑名单
            multipeSelectionPopup.setTx_5Text(getString(R.string.text_report));//举报
        }
        multipeSelectionPopup.showPopupWindow();
    }


    /**
     * 点赞
     */
    private void executeLike() {
        post.executeLike();
        homeListAdapter.notifyDataSetChanged();
        String url = URL_POST_LIKE + "/" + post.getStatistic().getPost_id() + "/praise";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                CommonEntity commonEntity = GsonUtil.fromJson(response, CommonEntity.class);
                if (commonEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                post.executeLike();
                homeListAdapter.notifyDataSetChanged();
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    /**
     * 关注用户
     */
    private void executeFollow() {
        swipeLayout.setRefreshing(true);
        String url = URL_FOLLOW_UNFOLLOW + post.getUser_id();
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                CommonEntity commonEntity = GsonUtil.fromJson(response, CommonEntity.class);
                if (commonEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    post.setIs_follow(commonEntity.getData().getStatus());
                    multipeSelectionPopup.dismiss();
                    if (commonEntity.getData().getStatus() == 1) {
                        ShowToast.showShortToast(getString(R.string.text_follow_success));
                    } else {
                        ShowToast.showShortToast(getString(R.string.text_follow_cancel));
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                multipeSelectionPopup.dismiss();
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    /**
     * 收藏
     */
    private void executeFav() {
        swipeLayout.setRefreshing(true);
        String url = URL_FAV_UNFAV + post.getId() + "/fav";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                CommonEntity commonEntity = GsonUtil.fromJson(response, CommonEntity.class);
                if (commonEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    post.setFav(commonEntity.getData().getStatus());
                    multipeSelectionPopup.dismiss();
                    if (commonEntity.getData().getStatus() == 1) {
                        ShowToast.showShortToast(getString(R.string.text_fav_success));
                    } else {
                        ShowToast.showShortToast(getString(R.string.text_fav_cancel));
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                multipeSelectionPopup.dismiss();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    // 添加好友
    private void addFriend() {
        multipeSelectionPopup.dismiss();
        if (mUserEntity.getData().getUser_id() == post.getUser_id()) {
            ShowToast.showShortToast(getString(R.string.not_add_myself));
            return;
        }
        if (friends == null) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        //demo use a hardcode reason here, you need let user to input if you like
                        String s = getResources().getString(R.string.Add_a_friend);
                        EMClient.getInstance().contactManager().addContact(post.getUser_id() + "", s);
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                String s1 = getResources().getString(R.string.send_successful);
                                ShowToast.showShortToast(s1);
                            }
                        });
                    } catch (final Exception e) {
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                String s2 = getResources().getString(R.string.Request_add_buddy_failure);
                                ShowToast.showShortToast(s2);
                            }
                        });
                    }
                }
            }).start();
        } else {
            startActivity(new Intent(getActivity(), ChatActivity.class).putExtra("userId", post.getUser_id() + ""));
        }
    }

    /**
     * 拉黑
     */
    private void executeBlack() {
        multipeSelectionPopup.dismiss();
        String url = URL_BLACKLIST + "/" + post.getUser_id();
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast(getString(R.string.text_add_black_list_success));
                homeListAdapter.getData().remove(post);
                homeListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    /**
     * 删除帖子
     */
    private void deletePost() {
        multipeSelectionPopup.dismiss();
        String url = URL_REPOT + post.getId() + "/disable";
        OkHttpUtils.put().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast(getString(R.string.text_post_delete_success));
                homeListAdapter.getData().remove(post);
                homeListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }


    /**
     * 举报
     */
    private void executeReport() {
        multipeSelectionPopup.dismiss();
        String url = URL_REPOT + post.getId() + "/report";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast(getString(R.string.text_report_success));
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    /**
     * 获取最新发布
     */
    private void getNewPublishData() {
        newPublishSel();
        requestType = PARAMS_REQUEST_TYPE_NEW;
        page = 1;
        getData();
    }

    /**
     * 获取离我最近的
     */
    private void getLocationData() {
        localtionSel();
        userLocation = SPUtil.getUserLocation();
        requestType = PARAMS_REQUEST_TYPE_LOCALTION;
        page = 1;
        getData();
    }

    /**
     * 最热主题
     */
    private void getHotData() {
        hotSel();
        requestType = PARAMS_REQUEST_TYPE_HOT;
        page = 1;
        getData();
    }

    /**
     * 关注
     */
    private void getFollowData() {
        followSel();
        requestType = PARAMS_REQUEST_TYPE_FOLLOW;
        page = 1;
        getData();
    }

    private void getData() {
        swipeLayout.setRefreshing(true);
        GetBuilder shopsBuilder = new GetBuilder();
        shopsBuilder.url(URL_INVITATION);
        shopsBuilder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        if (requestType != PARAMS_REQUEST_TYPE_FOLLOW)
            shopsBuilder.addParams("city_id", userLocation.getCityId());
//        shopsBuilder.addParams("city_id", userLocation.getHomeCityId());
        shopsBuilder.addParams("page", String.valueOf(page));
        shopsBuilder.addParams("size", String.valueOf(PARAMS_PAGE_SIZE));
        shopsBuilder.addParams("type", String.valueOf(requestType));
        shopsBuilder.addParams("lng", userLocation.getLongitude());
        shopsBuilder.addParams("lat", userLocation.getLatitude());
        shopsBuilder.addParams("category", classifyEntity.getId());
        shopsBuilder.build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                HomeListEntity homeListEntity = GsonUtil.fromJson(response, HomeListEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(homeListEntity.getStatus_code())) {
                    isEnd = homeListEntity.getData().getIs_end();
                    if (page == 1) {
                        homeListAdapter.setNewData(homeListEntity.getData().getList());
                        if (homeListEntity.getData().getList().size() == 0) {
                            view_empty.setVisibility(View.VISIBLE);
                        } else {
                            view_empty.setVisibility(View.GONE);
                        }
                    } else {
                        homeListAdapter.addData(homeListEntity.getData().getList());
                    }
                }
                homeListAdapter.loadMoreComplete();
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    /**
     * banner广告
     */
    private void getBanner() {
        bannerImages.clear();
        OkHttpUtils.get().url(URL_BANNERS)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("position", "1")
                .addParams("city_id", userLocation.getCityId())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                bannerEntity = GsonUtil.fromJson(response, BannerEntity.class);
                if (bannerEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    for (int i = 0; i < bannerEntity.getData().size(); i++) {
                        bannerImages.add(bannerEntity.getData().get(i).getCover());
                    }
                    initBannerData();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    private void showHead() {
        mUserEntity = SPUtil.getUser();
//        CommonUtils.loadImageView(getActivity(), mUserEntity.getData().getCover(), R.mipmap.default_head, iv_user_head);
    }


    @OnClick(R.id.ll_float_new_publish)
    void newPost() {
        getNewPublishData();
    }

    @OnClick(R.id.ll_float_location)
    void location() {
        getLocationData();
    }

    @OnClick(R.id.ll_float_hot)
    void hot() {
        getHotData();
    }

    @OnClick(R.id.ll_float_follow)
    void follow() {
        getFollowData();
    }


    private void replaceClassify() {
        ll_float_new_publish.setSelected(false);
        ll_float_location.setSelected(false);
        ll_float_hot.setSelected(false);
        ll_float_follow.setSelected(false);
    }

    private void replaceHeadClassify() {
        ll_new_publish.setSelected(false);
        ll_location.setSelected(false);
        ll_hot.setSelected(false);
        ll_follow.setSelected(false);
    }

    private void newPublishSel() {
        replaceClassify();
        replaceHeadClassify();
        ll_new_publish.setSelected(true);
        ll_float_new_publish.setSelected(true);
    }

    private void localtionSel() {
        replaceClassify();
        replaceHeadClassify();
        ll_location.setSelected(true);
        ll_float_location.setSelected(true);
    }

    private void hotSel() {
        replaceClassify();
        replaceHeadClassify();
        ll_hot.setSelected(true);
        ll_float_hot.setSelected(true);
    }

    private void followSel() {
        replaceClassify();
        replaceHeadClassify();
        ll_follow.setSelected(true);
        ll_float_follow.setSelected(true);
    }

    /**
     * 获取第一个可见Item的实时滚动高度
     */
    public int getScollYDistance() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) rv_list.getLayoutManager();
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = layoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        if (position > 0)
            return 350;
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }

    private void changeCityData(final String city) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                District district = DistrictCache.getInstance(getContext()).getCacheByName(city, CODE_CITY);
                if (null != district) {
                    userLocation.setCityId(district.getId());
                    userLocation.setCityName(city);
                    userLocation.setHomeCityId(district.getId());
                    userLocation.setHomeCityName(city);
                    SPUtil.putUserLocation(userLocation);
//                    userLocation = SPUtil.getUserLocation();
                    EventBus.getDefault().post(EVENT_CHANGE_CITY);
                    getData();
                    getBanner();
                }
            }
        });

    }


    @Override
    public void onRefresh() {
        userLocation = SPUtil.getUserLocation();
        homeListAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                homeListAdapter.getData().clear();
                userLocation = SPUtil.getUserLocation();
                initData();
                homeListAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    homeListAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        userLocation = SPUtil.getUserLocation();
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(getActivity(), R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        homeListAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == RESULT_OK) {
            if (data != null) {
                String city = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
                tv_address.setText(city);
                changeCityData(city);

            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mConvenientBanner.startTurning(3000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mConvenientBanner.stopTurning();
    }

    @Override
    public void onItemClick(int position) {
        if (position != 0) {
            String shopId = bannerEntity.getData().get(position).getShop_id();
            if (null == shopId || Integer.parseInt(shopId) <= 0 || shopId.length() > 9) {
                return;
            }

            startLocalActivity(ShopDetailActivity.class, PARAMS_SHOP_ID,
                    bannerEntity.getData().get(position).getShop_id());
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_USER_HEAD_UPDATE:
                showHead();
                break;
            case EVENT_SHARED_SUCCESS:
                post.getStatistic().addShared();
                homeListAdapter.notifyDataSetChanged();
                break;
            case EVENT_PARAMS_REPOST:
                post.getStatistic().addRePost();
                homeListAdapter.notifyDataSetChanged();
                break;
            case EVENT_PARAMS_COMMENT:
                post.getStatistic().addComment();
                homeListAdapter.notifyDataSetChanged();
                break;
            case EVENT_DELETE_COMMENT:
                post.getStatistic().subComment();
                homeListAdapter.notifyDataSetChanged();
                break;
            case EVENT_PARAMS_LIKE:
                post.executeLike();
                homeListAdapter.notifyDataSetChanged();
                break;
            case EVENT_BUY_POST_SUCCESS:
                post.buyPost();
                homeListAdapter.notifyDataSetChanged();
                break;
            case EVENT_DELETE_POST:
                if (null != post)
                    deletePost();
                break;
            case EVENT_UPDATE_USER_STATUS:
            case EVENT_VIP_CANCEL:
                initView();
                initData();
                initEvent();
                break;
            case EVENT_PUBLISH_POST_SUCCESS:
                initData();
                break;
        }
    }
}
